package com.ehaoyao.produce;

import com.alibaba.fastjson.JSONObject;
import com.ehaoyao.config.KafkaConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
 * <dl>
 * <dt>KafkaProduce</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2006</dd>
 * <dd>CreateDate: 2020/6/13</dd>
 * </dl>
 *
 * @author zhangyp
 */
@Component
@Slf4j
public class KafkaProduce {

    @Autowired
    private KafkaTemplate<String,Object> kafkaTemplate;

    public void send(Object objectj){
        String jsonStr = JSONObject.toJSONString(objectj);
        log.info("待发送消息为:"+jsonStr);
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(KafkaConfig.TOPIC_TEST,jsonStr);
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                log.info("消息发送失败,消息:{},失败原因:{}",jsonStr,throwable.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                log.info("消息发送成功,消息:{},返回结果{}",jsonStr,JSONObject.toJSONString(stringObjectSendResult));
            }
        });
    }
}
